package com.demo.serviceconsumer.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("/getNameByUserId/{id}")
    public String getNameByUserId(@PathVariable("id")int id){
        // 使用discoveryClient 可以从注册中心eureka 获取到服务的信息
        List<ServiceInstance> instances = discoveryClient.getInstances("server-provider");
        // 获取第一个服务信息
        ServiceInstance instanceInfo = instances.get(0);
        //获取ip
        String ip = instanceInfo.getHost();
        //获取port
        int port = instanceInfo.getPort();
        String url  ="http://"+ip+":"+port+"/user/getNameByUserId/"+id;
        String result = restTemplate.getForObject(url, String.class);
        System.out.println(url + "------"+result);
        return result;
    }
}
